<?php
    if(basename(__FILE__) == basename($_SERVER['PHP_SELF'])){exit();}
    include_once("backend/db/db_cse305.php")
?>
<div id="create_order_widget" class="widgetcontainer" <?php if (!isLoggedIn() || $_SESSION['User']->UserType == "Customer") echo "style='display:none;'"?>>
    <div id="create_order_heading" class="widgetheading">
        Manage Orders / View Customer Accounts<img src="images/plus.jpg"/>
    </div>
    <div id="create_order" class="widget">
        <script type="text/javascript">
            $("#create_order_heading").data("divlink", $("#create_order"));
            $("#create_order").data("heading", $("#create_order_heading"));
            $("#create_order_heading").data("clear", function() {
                $("#order_user_search_query").val("");
                $("#order_user_search_type").val("username");
                $("#order_user_search_table tbody > tr").remove();
                order_customer_accounts = null;
                order_cur_account = null;
                $("#create_order_accid").val("");
                $("#create_order_form")[0].reset();
                $("#edit_order_orderid").val("");
                $("#edit_order_id_label").text("");
            });
        </script>
        
        <div id="clear"></div>
        <div>
            <form>
                Customer Search: <input id="order_user_search_query" style="margin-left:10px;margin-right:10px;width:200px;" name="user_search_query" type="text" />
                Search Type: <select id="order_user_search_type" style="margin-left:10px;margin-right:30px;"><option value="username">User Name</option><option value="id">User ID</option><option value="lastname">Last Name</option></select>
                <input type="submit" class="button blue" value="Search" onclick="doCustomerLookup($('#order_user_search_query').val(), $('#order_user_search_type').val());return false;"/>
            </form>
            <br />
            <b>Click on a customer to see their accounts.</b>
            <table id="order_user_search_table" class="rounded-corner sortable">
                <thead style="text-align:center;"><tr>
                    <th>User ID</th><th>User Name</th><th>User Type</th><th>First Name</th><th>Last Name</th>
                </tr></thead>
                <tbody id="order_user_search_table_body">
                </tbody>
            </table>
            <hr />
            <h2 id="order_cur_customer"></h2>
            <b>Click on an account to create an order.</b>
            <table id="order_customer_accounts_table" class="rounded-corner sortable">
                <thead style="text-align:center;"><tr>
                    <th>Account ID</th><th>Date Opened</th><th>Account Value</th><th>Account Volume</th>
                </tr></thead>
                <tbody id="order_customer_accounts_table_body">
                </tbody>
            </table>
            <hr />
            <h3>Current Account Holdings<span id="order_customer_account_holding_id"></h3>
            
            <table id="order_customer_account_table" class="rounded-corner sortable">
                <thead style="text-align:center;"><tr>
                    <th>Stock Symbol</th><th>Stock Name</th><th>Number of Shares</th><th>Share Value</th><th>Total Value</th>
                </tr></thead>
                <tbody id="order_customer_account_table_body">
                </tbody>
            </table>
            <hr />
            <h3>Account Orders<span id="order_customer_account_order_id"></h3>
            <b>Click on an order to add transactions.</b>
            
            <table id="order_customer_order_table" class="rounded-corner sortable">
                <thead style="text-align:center;"><tr>
                    <th>Order ID</th><th>Stock Symbol</th><th>Order Type</th><th>Latest Transaction Time</th>
                </tr></thead>
                <tbody id="order_customer_order_table_body">
                </tbody>
            </table>
            
            <br/>
            <div id="create_order_result" style="display:none;"></div>
            <input id="create_order_accid" type="hidden" value=""/>
            <form id="create_order_form" style="display:none;">
                <table style="margin:auto;-moz-border-radius: 10px;-webkit-border-radius: 10px;border: 1px solid gray;padding: 10px;">
                    <tr><td colspan="2"><center><b>Create an order</b></center></td></tr>
                    <tr><td colspan="2" style="height:10px;"></td></tr>
                    <tr><td>Stock Symbol:</td><td><input id="create_order_stock_symbol" type='text' /></td></tr>
                    <tr><td>Order Type:</td><td><select id="create_order_ordertype"><option value="buy">Buy</option><option value="sell">Sell</option></select></td></tr>
                    <tr><td>Number of Shares:</td><td><input id="create_order_numshares" type='text' /></td></tr>
                    <tr><td>Fee:</td><td><input id="create_order_fee" type='text' /></td></tr>
                    <tr><td>Price Type:</td><td><select id="create_order_pricetype"><option value="market">Market</option><option value="close">Market on Close</option><option value="trailing">Trailing Stop</option><option value="hidden">Hidden Stop</option></select></td></tr>
                    <tr id="create_order_price_type_percent"><td>Percentage:</td><td><input id="create_order_percentage" type='text' /></td></tr>
                    <tr><td colspan="2" style="height:10px;"></td></tr>
                    <tr><td colspan="2"><center><input class="button blue" type='submit' value="Create" /></center></td></tr>
                </table>
            </form>
            <input id="edit_order_orderid" type="hidden" value=""/>
            <form id="edit_order_form" style="display:none;">
                <table style="margin:auto;-moz-border-radius: 10px;-webkit-border-radius: 10px;border: 1px solid gray;padding: 10px;">
                    <tr><td colspan="2"><center><b>Add Transaction to Order #</b><span id="edit_order_id_label"></span></center></td></tr>
                    <tr><td colspan="2" style="height:10px;"></td></tr>
                    <tr><td>Number of Shares:</td><td><input id="edit_order_numshares" type='text' /></td></tr>
                    <tr><td>Fee:</td><td><input id="edit_order_fee" type='text' /></td></tr>
                    <tr><td colspan="2" style="height:10px;"></td></tr>
                    <tr><td colspan="2"><center><input class="button blue" type='submit' value="Add Transaction" /></center></td></tr>
                </table>
            </form>
            
            <br/>
            
            <hr />
            <h3>Order Details<span id="order_customer_order_detail_id"></span></h3>
            <table id="order_customer_order_detail_table" class="rounded-corner sortable">
                <thead style="text-align:center;"><tr>
                    <th>Transaction ID</th><th>Number of Shares</th><th>Price/Transaction Type</th><th>Percentage</th><th>Fee</th><th>Employee</th><th>Transaction Time</th>
                </tr></thead>
                <tbody id="order_customer_order_detail_table_body">
                </tbody>
            </table>
        </div>
        
    </div>
    <br />
</div>
<script type="text/javascript">
    $("#create_order_pricetype").bind('change', function() {
        var v = $("#create_order_pricetype").val();
        if (v == "market" || v == "close") {
            $("#create_order_price_type_percent").hide();
        } else if (v == "trailing" || v == "hidden") {
            $("#create_order_price_type_percent").show();
        }
    });
    $('#create_order_form').bind('submit', function(e) {
        $("#create_order_result").hide();
        $.ajax({
            type: 'POST',
            url: '../backend/create_order.php',
            dataType: 'json',
            data: {
                op: 'create',
                accid: $("#create_order_accid").val(),
                stocksym: $("#create_order_stock_symbol").val(),
                ordertype: $("#create_order_ordertype").val(),
                numshares: $("#create_order_numshares").val(),
                fee: $("#create_order_fee").val(),
                pricetype: $("#create_order_pricetype").val(),
                percent: $("#create_order_percentage").val()
            },
            success: function(data) {
                if (data["Success"] != null) {
                    if (data["Success"] == 1) {
                        $('#create_order_form')[0].reset();
                        $("#create_order_result").text("Order successfully created.");
                        $("#create_order_result").attr("class", "success");
                        $("#create_order_result").show();
                    } else if (data["Success"] == 0) {
                        $("#create_order_result").text(data["Msg"]);
                        $("#create_order_result").attr("class", "error");
                        $("#create_order_result").show();
                    }
                }
            },                    
            error: function(XMLHttpRequest, textStatus, errorThrown) {
            }
        });
        e.preventDefault();
        return false;
        
    });
    $('#edit_order_form').bind('submit', function(e) {
        $("#create_order_result").hide();
        $.ajax({
            type: 'POST',
            url: '../backend/create_order.php',
            dataType: 'json',
            data: {
                op: 'edit',
                orderid: $("#edit_order_orderid").val(),
                numshares: $("#edit_order_numshares").val(),
                fee: $("#edit_order_fee").val()
            },
            success: function(data) {
                if (data["Success"] != null) {
                    if (data["Success"] == 1) {
                        $("#edit_order_form")[0].reset();
                        $("#create_order_result").text("Transaction successfully added.");
                        $("#create_order_result").attr("class", "success");
                        $("#create_order_result").show();
                    } else if (data["Success"] == 0) {
                        $("#create_order_result").text(data["Msg"]);
                        $("#create_order_result").attr("class", "error");
                        $("#create_order_result").show();
                    }
                }
            },                    
            error: function(XMLHttpRequest, textStatus, errorThrown) {
            }
        });
        e.preventDefault();
        return false;
    });
    function doCustomerLookup(query, type) {
        if (query == "") {
            $("#user_search_table tbody > tr").remove();
            var tr = $("<tr>");
            tr.append($("<td colspan='5'>").text("Please enter a search query!"));
            $("#user_search_table_body").append(tr);
            return;
        }
        $.ajax({
            type: 'POST',
            url: '../backend/user_lookup.php',
            dataType: 'json',
            data: {
                t: type,
                d: query,
                l: 'customer'
            },
            success: function(data) {
                $("#order_user_search_table tbody > tr").remove();
                var any = false;
                $.each(data, function(key, value) {
                    any = true;
                    var tr = $("<tr>");
                    tr.bind("click", function() {
                        var uid = $($(this).find("td")[0]).text();
                        var name = $($(this).find("td")[3]).text() + " " + $($(this).find("td")[4]).text();
                        $("#order_customer_accounts_table_body").empty();
                        $("#order_customer_account_table_body").empty();
                        $("#order_customer_order_table_body").empty();
                        $("#create_order_form").hide();
                        $("#edit_order_form").hide();
                        $("#create_order_accid").val("");
                        order_customer_accounts = null;
                        order_cur_account = null;
                        lookupCustomerAccounts(uid, name);
                    });
                    tr.append($("<td>").text(value["UserID"]));
                    tr.append($("<td>").text(value["UserName"]));
                    tr.append($("<td>").text(value["UserType"]));
                    tr.append($("<td>").text(value["FirstName"]));
                    tr.append($("<td>").text(value["LastName"]));
                    $("#order_user_search_table_body").append(tr);
                });
                if (!any) {
                    var tr = $("<tr>");
                    tr.append($("<td colspan='5'>").text("No users found!"));
                    $("#order_user_search_table_body").append(tr);
                }
            },                    
            error: function(XMLHttpRequest, textStatus, errorThrown) {
            }
        });
    }
    
    
    function lookupCustomerAccounts(uid, name) {
        $.ajax({
            type: 'POST',
            url: '../backend/customer_info.php',
            dataType: 'json',
            data: {
                userid: uid
            },
            success: function(data) {
                $("#order_cur_customer").text("Customer: " + name + " (" + uid + ")");
                order_customer_accounts = data;
                //<th>Account ID</th><th>Date Opened</th><th>Account Value</th><th>Account Volume</th>
                $.each(order_customer_accounts, function(accountID, acc) {
                    var row = $("<tr>");
                    row.append($("<td>").text(accountID));
                    row.append($("<td>").text(acc["DateOpened"]));
                    row.append($("<td style='text-align:right;'>").text(priceFormat(acc["Value"])));
                    row.append($("<td style='text-align:right;'>").text(acc["Volume"]));
                    $("#order_customer_accounts_table_body").append(row);
                });
                $("#order_customer_accounts_table_body tr").bind('click', function() {
                    $("#create_order_form").show();
                    $("#edit_order_form").hide();
                    $("#order_customer_account_table_body").empty();
                    var account = order_customer_accounts[$($(this).find("td")[0]).text()];
                    order_cur_account = account;
                    $("#create_order_accid").val($($(this).find("td")[0]).text());
                    //<th>Stock Symbol</th><th>Stock Name</th><th>Number of Shares</th><th>Account Value</th><th>Account Volume</th>
                    $.each(account["Holdings"], function(key, stock) {
                        var row = $("<tr>");
                        row.append($("<td>").text(stock["StockSymbol"]));
                        row.append($("<td>").text(stock["StockName"]));
                        row.append($("<td style='text-align:right;'>").text(stock["Shares"]));
                        row.append($("<td style='text-align:right;'>").text(priceFormat(stock["SharePrice"])));
                        row.append($("<td style='text-align:right;'>").text(priceFormat(stock["Shares"] * stock["SharePrice"])));
                        $("#order_customer_account_table_body").append(row);
                    });
                    var last = $("<tr style='font-weight:bold;'>");
                    last.append($("<td>").text("Total"));
                    last.append($("<td>"));
                    last.append($("<td style='text-align:right;'>").text($($(this).find("td")[3]).text()));
                    last.append($("<td style='text-align:right;'>"));
                    last.append($("<td style='text-align:right;'>").text($($(this).find("td")[2]).text()));
                    $("#order_customer_account_table_body").append(last);
                    
                    $("#order_customer_order_table_body").empty();
                    $.each(account["Orders"], function(OrderID, Order) {
                        var row = $("<tr>");
                        row.append($("<td>").text(OrderID));
                        row.append($("<td>").text(Order["StockSymbol"]));
                        row.append($("<td>").text(Order["OrderType"]));
                        
                        var lastTime = null;
                        $.each(Order["TransactionHistory"], function(TransactKey, Transact) {
                            var date = 
                                new Date(
                                    Transact["Time"].substr(0, 4), 
                                    Transact["Time"].substr(5, 2), 
                                    Transact["Time"].substr(8, 2), 
                                    Transact["Time"].substr(11, 2), 
                                    Transact["Time"].substr(14, 2),
                                    Transact["Time"].substr(17, 2), 0);
                            if (lastTime == null) {
                                lastTime = date;
                            } else {
                                if (date > lastTime) {
                                    lastTime = date;
                                }
                            }
                        });
                        row.append($("<td>").text(lastTime.getFullYear() + "-" + pad(lastTime.getMonth() + 1) + "-" + pad(lastTime.getDate()) + " " + lastTime.toLocaleTimeString()));
                        $("#order_customer_order_table_body").append(row);
                    });
                    $("#order_customer_order_table_body tr").bind('click', function() {
                        
                        
                        
                        //alert($($(this).find("td")[0]).text());
                        $("#order_customer_order_detail_table_body").empty();
                        var order = order_cur_account["Orders"][$($(this).find("td")[0]).text()];
                        $("#edit_order_orderid").val($($(this).find("td")[0]).text());
                        $("#edit_order_id_label").text($($(this).find("td")[0]).text());
                        $("#edit_order_form").show();
                        $("#create_order_form").hide();
                        
                        $.each(order["TransactionHistory"], function(key, transact) {
                            var row = $("<tr>");
                            row.append($("<td>").text(transact["TransactionID"]));
                            row.append($("<td>").text(transact["NumShares"]));
                            row.append($("<td>").text(transact["PriceType"]));
                            if (transact["Percentage"] == null) {
                                row.append($("<td>").text("N/A"));
                            } else {
                                row.append($("<td>").text(String(transact["Percentage"]) + "%"));
                            }
                            row.append($("<td>").text(transact["Fee"]));
                            row.append($("<td>").text(transact["EmployeeName"] + " (" + transact["EmployeeID"] + ")"));
                            var date = 
                                    new Date(
                                    transact["Time"].substr(0, 4), 
                                    transact["Time"].substr(5, 2), 
                                    transact["Time"].substr(8, 2), 
                                    transact["Time"].substr(11, 2), 
                                    transact["Time"].substr(14, 2),
                                    transact["Time"].substr(17, 2), 0);
                            row.append($("<td>").text(date.getFullYear() + "-" + pad(date.getMonth() + 1) + "-" + pad(date.getDate()) + " " + date.toLocaleTimeString()));
                            $("#order_customer_order_detail_table_body").append(row);
                        });
                        $("#order_customer_order_detail_id").text(" - Order ID " + $($(this).find("td")[0]).text());
                    });
                    $("#order_customer_account_holding_id").text(" - Account ID " + $($(this).find("td")[0]).text());
                    $("#order_customer_account_order_id").text(" - Account ID " + $($(this).find("td")[0]).text());
                });
    
            },                    
            error: function(XMLHttpRequest, textStatus, errorThrown) {
            }
        });
    }
</script>